﻿// ....................................................................................................................
//	Author: Copyright (C) 2012 Ing. Marek Hubal
//	Email: hubal@acasoftware.org
// ....................................................................................................................

using System;

namespace core
{
    /// <summary>Trieda IGlobalData</summary>
	public class IGlobalData : IDisposable
	{
        public IParamList App_HistoryLists; // Ulozena historia textboxov aplikacie
        public IHistoryList FileExplorer_ExpandHistory; // Historia uspesnych expandovani
        public IHotPaths FileExplorer_HotPaths; // Objekt pre uchovanie "horucich ciet"
        public System.Collections.Generic.Dictionary<string, string> FileExplorer_Cache; // Objekt pre uchovanie cache obsahu INodeList
        public IFilterStorage FileExplorer_Filters; // Ulozene filtre
        public IParamList AppPanels_StartSettings; // Ulozene nastavenia panelov pre inicializaciu po starte aplikacie
        public IParamList UpdateData; // Data o poslednej zistenej verzii na internete
        public System.Collections.Generic.Dictionary<string, string> PasswordCache; // Objekt pre uchovanie cache hesiel
        public System.Collections.Generic.List<ICloudStorageDef> CloudStorages; // Zoznam cloudovych ulozisk
        public System.Collections.Generic.List<IConnectionProvider> ConnectionProviders; // Zoznam poskytovatelov spojenia
        public string FileExplorer_CompressionSettings; // Nastavenie kompresie
        public string FileExplorer_ExportListSettings; // Export zaznamov do suboru
        public string FileExplorer_EncryptSettings; // Nastavenie sifrovania
        public string FileExplorer_DecryptSettings; // Nastavenie desifrovania
        public string FileExplorer_ExtractCDContentSettings; // Nastavenie ripovania CD/DVD
        public string FileExplorer_SearchSettings; // Nastavenie hladania

        public DateTime LastCloudStoragesChanged; // Cas poslednej zmeny zoznamu inet. zariadeni

        /// <summary>Serializacia zoznamu inet. zariadeni</summary>
        /// <returns>serializovany obsah do retazca</returns>
        protected string SerializeCloudStorages()
        {
            using (System.IO.MemoryStream MS = new System.IO.MemoryStream())
            {
                using (System.IO.BinaryWriter W = new System.IO.BinaryWriter(MS))
                {
                    foreach (ICloudStorageDef C in CloudStorages)
                    {
                        W.Write(C.Type);
                        C.Serialize(W);
                    }
                    return ICore.Base64EncodeData(MS.ToArray());
                }
            }
        }
        /// <summary>Deserializacia zoznamu inet. zariadeni</summary>
        /// <param name="pData"></param>
        protected void DeserializeCloudStorages(string pData)
        {
            try
            {
                if (string.IsNullOrEmpty(pData)) return; // Nic nie je serializovane?
                using (System.IO.BinaryReader R = new System.IO.BinaryReader(new System.IO.MemoryStream(ICore.Base64DecodeData(pData))))
                {
                    while (true)
                    {
                        int Type = R.ReadInt32(); // Ziskam typ
                        switch (Type)
                        {
                            case ICloudStorageDef.TYPE_FTP:
                                {
                                    IFTPStorageDef C = new IFTPStorageDef(); // FTP definicia
                                    C.Deserialize(R); // Deserializujem
                                    CloudStorages.Add(C); // Zaradim
                                } break;
                        }
                    }
                }
            }
            catch
            {
            }
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
        }

        /// <summary>Konstruktor</summary>
        public IGlobalData()
        {
            App_HistoryLists = new IParamList();
            FileExplorer_ExpandHistory = new IHistoryList(); FileExplorer_ExpandHistory.Capacity = 20;
            FileExplorer_HotPaths = new IHotPaths();
            FileExplorer_Cache = new System.Collections.Generic.Dictionary<string, string>();
            FileExplorer_Filters = new IFilterStorage();
            AppPanels_StartSettings = new IParamList();
            UpdateData = null;
            PasswordCache = new System.Collections.Generic.Dictionary<string, string>();
            CloudStorages = new System.Collections.Generic.List<ICloudStorageDef>();
            ConnectionProviders = new System.Collections.Generic.List<IConnectionProvider>();
            FileExplorer_CompressionSettings = "";
            FileExplorer_ExportListSettings = "";
            FileExplorer_EncryptSettings = "";
            FileExplorer_DecryptSettings = "";
            FileExplorer_ExtractCDContentSettings = "";
        }
        /// <summary>Dispose metoda</summary>
        public void Dispose()
        {
            App_HistoryLists = (IParamList)ICore.DisposeObject(App_HistoryLists);
            FileExplorer_ExpandHistory = (IHistoryList)ICore.DisposeObject(FileExplorer_ExpandHistory);
            FileExplorer_HotPaths = (IHotPaths)ICore.DisposeObject(FileExplorer_HotPaths);
            FileExplorer_Filters = (IFilterStorage)ICore.DisposeObject(FileExplorer_Filters);
            if (FileExplorer_Cache != null) FileExplorer_Cache.Clear();
            FileExplorer_Cache = null;
            AppPanels_StartSettings = (IParamList)ICore.DisposeObject(AppPanels_StartSettings);
            UpdateData = (IParamList)ICore.DisposeObject(UpdateData);
            PasswordCache = null;
            CloudStorages = null;
            for (int i = 0; i < ConnectionProviders.Count; i++) ConnectionProviders[i].Dispose();
            ConnectionProviders = null;
        }

        /// <summary>Vymazanie obsahu</summary>
        public void Clear()
        {
            App_HistoryLists.Clear();
            FileExplorer_ExpandHistory.Clear();
            FileExplorer_HotPaths.Clear();
            FileExplorer_Cache.Clear();
            FileExplorer_Filters.Clear();
            AppPanels_StartSettings.Clear();
            UpdateData.Clear();
            PasswordCache.Clear();
            CloudStorages.Clear();
            for (int i = 0; i < ConnectionProviders.Count; i++) ConnectionProviders[i].Dispose();
            ConnectionProviders.Clear();
            FileExplorer_CompressionSettings = "";
            FileExplorer_ExportListSettings = "";
            FileExplorer_EncryptSettings = "";
            FileExplorer_DecryptSettings = "";
            FileExplorer_ExtractCDContentSettings = "";
        }

        /// <summary>Nacitanie z konfiguracie</summary>
        public void Load()
        {
            App_HistoryLists.Deserialize(IApp.Config.GetParam("APP_LIST_HISTORY", ""), true);
            FileExplorer_ExpandHistory.Deserialize(IApp.Config.GetParam("FILE_EXPLORER_EXPAND_HISTORY", ""), true);
            FileExplorer_HotPaths.Deserialize(IApp.Config.GetParam("FILE_EXPLORER_HOTS_PATHS", ""), true);
            FileExplorer_Filters.Deserialize(IApp.Config.GetParam("FILE_EXPLORER_FILTERS", ""), true);
            AppPanels_StartSettings.Deserialize(IApp.Config.GetParam("APP_PANELS_INIT_SETTINGS", ""), true);
            DeserializeCloudStorages(IApp.App.LoadOtherConfig_CloudStorages());
            FileExplorer_CompressionSettings = IApp.Config.GetParam("FILE_EXPLORER_COMPRESSION_SETTINGS", "");
            FileExplorer_ExportListSettings = IApp.Config.GetParam("FILE_EXPLORER_EXPORT_LIST_SETTINGS", "");
            FileExplorer_ExtractCDContentSettings = IApp.Config.GetParam("FILE_EXPLORER_CD_EXTRACT_SETTINGS", "");
        }
        /// <summary>Ulozenie do konfiguracie</summary>
        public void Save()
        {
            IApp.Config.SetParam("APP_LIST_HISTORY", App_HistoryLists.Serialize(true));
            IApp.Config.SetParam("FILE_EXPLORER_EXPAND_HISTORY", FileExplorer_ExpandHistory.Serialize(true));
            IApp.Config.SetParam("FILE_EXPLORER_HOTS_PATHS", FileExplorer_HotPaths.Serialize(true));
            IApp.Config.SetParam("FILE_EXPLORER_FILTERS", FileExplorer_Filters.Serialize(true));
            IApp.Config.SetParam("APP_PANELS_INIT_SETTINGS", AppPanels_StartSettings.Serialize(true));
            IApp.Config.SetParam("FILE_EXPLORER_COMPRESSION_SETTINGS", FileExplorer_CompressionSettings);
            IApp.Config.SetParam("FILE_EXPLORER_EXPORT_LIST_SETTINGS", FileExplorer_ExportListSettings);
            IApp.Config.SetParam("FILE_EXPLORER_CD_EXTRACT_SETTINGS", FileExplorer_ExtractCDContentSettings);
        }

        /// <summary>Ziskanie hesla z cache</summary>
        /// <param name="pID">ID objektu</param>
        /// <returns>heslo alebo null</returns>
        public string GetPassword(string pID)
        {
            if (!PasswordCache.ContainsKey(pID)) return null; // Nie je v cache?
            return PasswordCache[pID]; // Vratim heslo
        }
        /// <summary>Ulozenie hesla do cache</summary>
        /// <param name="pID">ID objektu</param>
        /// <param name="pValue">nova hodnota alebo null pre odstranenie</param>
        public void SavePassword(string pID, string pValue)
        {
            if (pValue == null) // Idem odstranovat?
            {
                if (PasswordCache.ContainsKey(pID)) PasswordCache.Remove(pID); // Vymazem z cache
                return;
            }
            if (PasswordCache.ContainsKey(pID)) PasswordCache[pID] = pValue; // Existuje?
            else PasswordCache.Add(pID, pValue);
        }

        /// <summary>Ulozenie nastavenia cloud zariadeni do konfiguracie</summary>
        public void SaveCloudStoragesToConfiguration()
        {
            IApp.App.SaveOtherConfig_CloudStorages(SerializeCloudStorages());
        }
        /// <summary>Ziskanie poskytovatela spojenia</summary>
        /// <param name="pID">ID</param>
        /// <returns>objekt alebo null</returns>
        public IConnectionProvider GetConnectionProvider(int pID)
        {
            for (int i = 0; i < ConnectionProviders.Count; i++) // Hladam existujuce
            {
                if (ConnectionProviders[i].ID == pID) return ConnectionProviders[i];
            }

            for (int i = 0; i < CloudStorages.Count; i++) // Prehladavam definicie
            {
                if (CloudStorages[i].ID == pID) // Nasiel som definiciu?
                {
                    switch (CloudStorages[i].Type) // Vytvorim prislusny provider
                    {
                        case ICloudStorageDef.TYPE_FTP:
                            {
                                IFTPConnectionProvider P = new IFTPConnectionProvider((IFTPStorageDef)CloudStorages[i]); // Vytvorim novy provider
                                ConnectionProviders.Add(P); // Zaradim do zoznamu
                                return P;
                            }
                    }
                }
            }
            return null; // Ziadny existujuci provider ani jeho definicia neboli najdeni
        }
        /// <summary>Vymazanie vsetkych spojeni</summary>
        public void ClearConnectionProviders()
        {
            for (int i = 0; i < ConnectionProviders.Count; i++) // Zrusim vsetky alokovane spojenia
            {
                ConnectionProviders[i].Dispose();
            }
            ConnectionProviders.Clear(); // Vymazem zoznam
            CloudStorages.Clear(); // Vymazem zoznam definicii
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
            SaveCloudStoragesToConfiguration();
        }
        /// <summary>Vymazanie vsetkych spojeni</summary>
        public void ClearConnectionProviders(int pID)
        {
            for (int i = CloudStorages.Count - 1; i >= 0; i--) // Zrusim vsetky alokovane spojenia daneho typu
            {
                if (CloudStorages[i].Type == pID) { // Je to spojenie zadaneho typu?

                    for (int j = ConnectionProviders.Count - 1; j >= 0; j--) // Vymazem vsetkych pokytovatelov
                    {
                        if (ConnectionProviders[j].ID == CloudStorages[i].ID)
                        {
                            ConnectionProviders[j].Dispose();
                            ConnectionProviders.RemoveAt(j);
                        }
                    }
                    CloudStorages.RemoveAt(i);
                }
            }
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
            SaveCloudStoragesToConfiguration();
        }
        /// <summary>Vymazanie definicia a jeho spojeni</summary>
        /// <param name="pID">ID</param>
        public void DeleteStorageDef(int pID)
        {
            for (int i = CloudStorages.Count - 1; i >= 0; i--) // Zrusim vsetky alokovane spojenia daneho typu
            {
                if (CloudStorages[i].ID == pID)
                { // Je to spojenie zadaneho typu?

                    for (int j = ConnectionProviders.Count - 1; j >= 0; j--) // Vymazem vsetkych pokytovatelov
                    {
                        if (ConnectionProviders[j].ID == CloudStorages[i].ID)
                        {
                            ConnectionProviders[j].Dispose();
                            ConnectionProviders.RemoveAt(j);
                        }
                    }
                    CloudStorages.RemoveAt(i);
                }
            }
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
            SaveCloudStoragesToConfiguration();
        }
        /// <summary>Ziskanie objektu definicie spojenia</summary>
        /// <param name="pID">ID</param>
        /// <returns>objekt alebo null</returns>
        public ICloudStorageDef GetStorageDef(int pID)
        {
            foreach (ICloudStorageDef C in CloudStorages)
            {
                if (C.ID == pID) return C; // Porovnam a vratim ak je zhoda
            }
            return null; // Nic som nenasiel
        }
        /// <summary>Aktualizacia definicie spojenia</summary>
        /// <param name="pValue">hodnota</param>
        public void UpdateStorageDef(ICloudStorageDef pValue)
        {
            foreach (IConnectionProvider P in ConnectionProviders) // Hladam prislusne spojenia
            {
                if (P.ID == pValue.ID) P.UpdateStorageDefs(pValue); // Aktualizujem
            }
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
            SaveCloudStoragesToConfiguration();
        }
        /// <summary>Zaradenie definicie spojenia</summary>
        /// <param name="pValue">objekt</param>
        public void AddStorageDef(ICloudStorageDef pValue)
        {
            CloudStorages.Add(pValue); // Zaradim
            LastCloudStoragesChanged = DateTime.Now; // Nastavim datum zmeny
            SaveCloudStoragesToConfiguration();
        }

        /// <summary>Ziskanie hotpath connection providera pre zadane ID</summary>
        /// <param name="pID">ID</param>
        /// <returns>vysledok</returns>
        public string GetHotPathConnectionProvider(int pID)
        {
            foreach (IConnectionProvider P in ConnectionProviders)
            {
                if (P.ID == pID) return P.HotPathConnectionProvider;
            }
            return "";
        }
        /// <summary>Ziskanie ID z Hotpath ID</summary>
        /// <param name="pID">hodtpath ID</param>
        /// <returns>vysledok</returns>
        public int GetConnProviderFromHotPathConnProvider(string pID) 
        {
            foreach (ICloudStorageDef P in CloudStorages)
            {
                if (P.HotPathConnectionProvider == pID) return GetConnectionProvider(P.ID).ID;
            }
            return 0;
        }
    }
}
 